<template>
  <div ref="threejsContainer" style="width: 100%; height: 700px;">
    threejs
  </div>
</template>

<script>
import * as THREE from "three";

export default {
  name: "ThreeDemo",
  mounted() {
    this.initThreejs();
  },
  data() {
    return {

    }
  },
  methods: {
    created() {

    },
    initThreejs() {
      // 创建场景
      const scene = new THREE.Scene();

      // 创建相机
      const camera = new THREE.PerspectiveCamera(
        50,
        this.$refs.threejsContainer.offsetWidth / this.$refs.threejsContainer.offsetHeight,
        0.1,
        1000
      );
      camera.position.z = 8;

      // 创建渲染器
      const renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(
        this.$refs.threejsContainer.offsetWidth,
        this.$refs.threejsContainer.offsetHeight
      );
      this.$refs.threejsContainer.appendChild(renderer.domElement);

      // 创建几何体
      const geometry = new THREE.BoxGeometry(2, 2, 2);
      // 创建材质
      const material = new THREE.MeshStandardMaterial({ color: 0x00fff0 });
      // 创建网格对象
      const cube = new THREE.Mesh(geometry, material);

      const cube2=new THREE.Mesh(
        new THREE.BoxGeometry(2, 2, 2),
        new THREE.MeshStandardMaterial({ color: 0xff0000 })
      );
      cube2.position.x=-3;
      // 将网格对象添加到场景
      scene.add(cube,cube2);

      // 环境光
      const ambientLight = new THREE.AmbientLight(0xa0a0a0);
      scene.add(ambientLight);

      // 点光源
      const pointLight = new THREE.PointLight(0xffffff, 1, 100);
      pointLight.position.set(5, 5, 5);
      scene.add(pointLight);

      // 渲染循环
      const animate = () => {
        requestAnimationFrame(animate);
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;

        cube2.rotation.x += 0.01;
        cube2.rotation.y -= 0.01;
        renderer.render(scene, camera);
      };
      animate();


    }
  }

}
</script>

<style scoped lang="scss">

</style>
